package org.springblade.tms.module.gps.kafka;

import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.system.feign.IDictBizClient;
import org.springblade.tms.global.constant.DictCodeConstant;
import org.springblade.tms.global.utils.RSAUtils;
import org.springblade.tms.module.gps.base.GPSService;
import org.springblade.tms.module.gps.vo.GPSAlarmVO;
import org.springblade.tms.module.gps.vo.GPSFenceVO;
import org.springblade.tms.module.roadbook.entity.TMRoadBook;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListener;

import javax.annotation.Resource;
import java.util.UUID;

import static org.springblade.common.constant.TenantConstant.DEFAULT_TENANT_ID;
import static org.springblade.tms.global.constant.GpsConstant.*;

/**
 * @projectName: BladeX
 * @package: org.springblade.tms.module.gps.kafka
 * @className: GpsListener
 * @author: yr
 * @description: gpskafka监听器
 * @date: 2022/5/18 15:43
 */
@Configuration
public class GpsListener {
	@Resource
	private GPSService gpsService;
	@Resource
	private BladeLogger bladeLogger;
	@Resource
	private IDictBizClient dictBiz;

	/**
	 * @param data:
	 * @return R<Boolean>
	 * @author yr
	 * @description kafka监听器
	 * @date 2022/5/18 16:55
	 */
	@SneakyThrows
	@KafkaListener(id = GROUP_ID, topics = TOPIC, groupId = GROUP_ID)
	public void earlyWarningInformationPush(String data, ConsumerRecord<?, ?> record) {
		bladeLogger.info("kafka" + UUID.randomUUID() + "请求key", record.key().toString());
		String privateKey = dictBiz.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.PRIVATE_KEY_KAFKA, DEFAULT_TENANT_ID).getData();
		bladeLogger.info("kafka" + UUID.randomUUID() + "解密私钥", privateKey);
		bladeLogger.info("kafka" + UUID.randomUUID() + "原始data", data);
		String decrypt = RSAUtils.decrypt(data, privateKey);
		bladeLogger.info("kafka" + UUID.randomUUID() + "请求参数", decrypt);
		//电子围栏监听
		if (record.key().equals(FENCE_LOG)) {
			GPSFenceVO gpsFenceVO = JSONUtil.toBean(decrypt, GPSFenceVO.class);
			gpsService.inAndOutOfTheElectronicFence(gpsFenceVO);
			//预警监听
		} else if (record.key().equals(ALARM_LOG)) {
			GPSAlarmVO gpsAlarmVO = JSONUtil.toBean(decrypt, GPSAlarmVO.class);
			gpsService.earlyWarningInformationPush(gpsAlarmVO);
		} else if (record.key().equals(GENTLY_ROUTE_PLAN)) {
			TMRoadBook roadBook = JSONUtil.toBean(decrypt, TMRoadBook.class);
			gpsService.eRoadBook(roadBook);
		}
	}
}
